package cn.devzyh.oms.coms.express.service.impl;

import cn.devzyh.oms.common.core.message.ComsErrorCodes;
import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.coms.api.express.entity.Express;
import cn.devzyh.oms.coms.api.order.entity.OrderHeader;
import cn.devzyh.oms.coms.express.mapper.ExpressMapper;
import cn.devzyh.oms.coms.express.service.ExpressService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
public class ExpressServiceImpl extends ServiceImpl<ExpressMapper, Express> implements ExpressService {

	@Override
	public R<String> match(OrderHeader header) {
		// 查询发货仓快递列表
		LambdaQueryWrapper<Express> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(Express::getWarehouseCode, header.getWarehouseCode());
		wrapper.eq(Express::getReceiveCountry, header.getReceiveCountry());
		wrapper.eq(Express::getReceiveState, header.getReceiveState());
		if (StrUtil.isNotBlank(header.getExpressCode())) {
			wrapper.eq(Express::getExpressCode, header.getExpressCode());
		}

		List<Express> expressList = list(wrapper);
		if (CollectionUtil.isEmpty(expressList)) {
			return R.failedMessage(ComsErrorCodes.EXPRESS_MATCH_FAILED, header.getExpressCode());
		}

		expressList = CollectionUtil.sort(expressList, Comparator.comparingInt(Express::getFreight));

		return R.ok(expressList.get(0).getExpressCode());
	}

}